import React, { useState, useMemo } from 'react';
import {
  Box,
  Card,
  CardContent,
  Typography,
  TextField,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Grid,
  Chip,
  IconButton,
  Menu,
  Paper,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TablePagination,
  Tooltip,
  Avatar,
  Alert,
  Button,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Accordion,
  AccordionSummary,
  AccordionDetails
} from '@mui/material';
import {
  Search as SearchIcon,
  MoreVert as MoreVertIcon,
  Visibility as VisibilityIcon,
  Download as DownloadIcon,
  Refresh as RefreshIcon,
  FilterList as FilterListIcon,
  History as HistoryIcon,
  Person as PersonIcon,
  Event as EventIcon,
  ExpandMore as ExpandMoreIcon,
  Warning as WarningIcon,
  CheckCircle as CheckCircleIcon,
  Error as ErrorIcon,
  Info as InfoIcon
} from '@mui/icons-material';
import { useQuery } from '@tanstack/react-query';
import { format } from 'date-fns';
import { zhCN } from 'date-fns/locale';
import { PageHeader } from '@/components/common/PageHeader';
import { settingsService } from '@/services/settingsService';
import type { AuditLog } from '@/types';

const AuditLogsPage: React.FC = () => {
  const [page, setPage] = useState(0);
  const [pageSize, setPageSize] = useState(10);
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedAction, setSelectedAction] = useState<string>('all');
  const [selectedLevel, setSelectedLevel] = useState<string>('all');
  const [selectedUser, setSelectedUser] = useState<string>('all');
  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
  const [selectedLog, setSelectedLog] = useState<AuditLog | null>(null);
  const [detailDialogOpen, setDetailDialogOpen] = useState(false);
  const [dateRange, setDateRange] = useState<'today' | 'week' | 'month' | 'all'>('week');

  // 获取审计日志
  const { data: auditLogsData, isLoading, refetch } = useQuery({
    queryKey: ['audit-logs', page, pageSize, searchTerm, selectedAction, selectedLevel, selectedUser, dateRange],
    queryFn: () => settingsService.getAuditLogs({
      page: page + 1,
      pageSize,
      search: searchTerm,
      action: selectedAction === 'all' ? undefined : selectedAction,
      level: selectedLevel === 'all' ? undefined : selectedLevel,
      userId: selectedUser === 'all' ? undefined : selectedUser,
      dateRange: dateRange === 'all' ? undefined : dateRange
    })
  });

  const auditLogs = auditLogsData?.items || [];
  const total = auditLogsData?.total || 0;

  // 日志级别颜色映射
  const getLevelColor = (level: string) => {
    switch (level) {
      case 'info': return 'primary';
      case 'success': return 'success';
      case 'warning': return 'warning';
      case 'error': return 'error';
      default: return 'default';
    }
  };

  // 日志级别图标
  const getLevelIcon = (level: string) => {
    switch (level) {
      case 'info': return <InfoIcon fontSize="small" />;
      case 'success': return <CheckCircleIcon fontSize="small" />;
      case 'warning': return <WarningIcon fontSize="small" />;
      case 'error': return <ErrorIcon fontSize="small" />;
      default: return <HistoryIcon fontSize="small" />;
    }
  };

  // 操作类型映射
  const getActionText = (action: string) => {
    const actionMap: Record<string, string> = {
      'user.login': '用户登录',
      'user.logout': '用户登出',
      'user.create': '创建用户',
      'user.update': '更新用户',
      'user.delete': '删除用户',
      'role.create': '创建角色',
      'role.update': '更新角色',
      'role.delete': '删除角色',
      'tenant.create': '创建租户',
      'tenant.update': '更新租户',
      'tenant.delete': '删除租户',
      'settings.update': '更新设置'
    };
    return actionMap[action] || action;
  };

  const handlePageChange = (event: unknown, newPage: number) => {
    setPage(newPage);
  };

  const handlePageSizeChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setPageSize(parseInt(event.target.value, 10));
    setPage(0);
  };

  const handleViewDetail = (log: AuditLog) => {
    setSelectedLog(log);
    setDetailDialogOpen(true);
  };

  const handleMenuClick = (event: React.MouseEvent<HTMLElement>) => {
    setAnchorEl(event.currentTarget);
  };

  const handleMenuClose = () => {
    setAnchorEl(null);
  };

  const handleExportLogs = () => {
    // 导出日志功能
    handleMenuClose();
  };

  // 过滤日志
  const filteredLogs = useMemo(() => {
    return auditLogs.filter((log: AuditLog) => {
      const matchesSearch = !searchTerm ||
        log.action.toLowerCase().includes(searchTerm.toLowerCase()) ||
        log.description.toLowerCase().includes(searchTerm.toLowerCase()) ||
        log.user?.name.toLowerCase().includes(searchTerm.toLowerCase());
      
      return matchesSearch;
    });
  }, [auditLogs, searchTerm]);

  return (
    <Box sx={{ p: 3 }}>
      <PageHeader
        title="审计日志"
        description="查看系统操作日志和安全事件"
        action={
          <Box sx={{ display: 'flex', gap: 1 }}>
            <Button
              variant="outlined"
              startIcon={<RefreshIcon />}
              onClick={() => refetch()}
            >
              刷新
            </Button>
            <IconButton onClick={handleMenuClick}>
              <MoreVertIcon />
            </IconButton>
            <Menu
              anchorEl={anchorEl}
              open={Boolean(anchorEl)}
              onClose={handleMenuClose}
            >
              <MenuItem onClick={handleExportLogs}>
                <DownloadIcon sx={{ mr: 1 }} />
                导出日志
              </MenuItem>
            </Menu>
          </Box>
        }
      />

      {/* 搜索和筛选 */}
      <Card sx={{ mb: 3 }}>
        <CardContent>
          <Grid container spacing={2} alignItems="center">
            <Grid item xs={12} md={3}>
              <TextField
                fullWidth
                placeholder="搜索操作、描述或用户..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                InputProps={{
                  startAdornment: <SearchIcon sx={{ color: 'text.secondary', mr: 1 }} />
                }}
              />
            </Grid>
            <Grid item xs={12} md={2}>
              <FormControl fullWidth>
                <InputLabel>时间范围</InputLabel>
                <Select
                  value={dateRange}
                  label="时间范围"
                  onChange={(e) => setDateRange(e.target.value as any)}
                >
                  <MenuItem value="today">今天</MenuItem>
                  <MenuItem value="week">近一周</MenuItem>
                  <MenuItem value="month">近一月</MenuItem>
                  <MenuItem value="all">全部</MenuItem>
                </Select>
              </FormControl>
            </Grid>
            <Grid item xs={12} md={2}>
              <FormControl fullWidth>
                <InputLabel>操作类型</InputLabel>
                <Select
                  value={selectedAction}
                  label="操作类型"
                  onChange={(e) => setSelectedAction(e.target.value as string)}
                >
                  <MenuItem value="all">全部操作</MenuItem>
                  <MenuItem value="user.login">用户登录</MenuItem>
                  <MenuItem value="user.create">创建用户</MenuItem>
                  <MenuItem value="role.create">创建角色</MenuItem>
                  <MenuItem value="settings.update">更新设置</MenuItem>
                </Select>
              </FormControl>
            </Grid>
            <Grid item xs={12} md={2}>
              <FormControl fullWidth>
                <InputLabel>日志级别</InputLabel>
                <Select
                  value={selectedLevel}
                  label="日志级别"
                  onChange={(e) => setSelectedLevel(e.target.value as string)}
                >
                  <MenuItem value="all">全部级别</MenuItem>
                  <MenuItem value="info">信息</MenuItem>
                  <MenuItem value="success">成功</MenuItem>
                  <MenuItem value="warning">警告</MenuItem>
                  <MenuItem value="error">错误</MenuItem>
                </Select>
              </FormControl>
            </Grid>
            <Grid item xs={12} md={3}>
              <Typography variant="body2" color="text.secondary" align="right">
                共 {total} 条日志，显示 {filteredLogs.length} 条
              </Typography>
            </Grid>
          </Grid>
        </CardContent>
      </Card>

      {/* 日志列表 */}
      <Card>
        <TableContainer>
          <Table>
            <TableHead>
              <TableRow>
                <TableCell>时间</TableCell>
                <TableCell>级别</TableCell>
                <TableCell>操作类型</TableCell>
                <TableCell>操作用户</TableCell>
                <TableCell>描述</TableCell>
                <TableCell>IP 地址</TableCell>
                <TableCell align="center">操作</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {isLoading ? (
                <TableRow>
                  <TableCell colSpan={7} align="center">
                    <Typography>加载中...</Typography>
                  </TableCell>
                </TableRow>
              ) : filteredLogs.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={7} align="center">
                    <Alert severity="info">暂无审计日志数据</Alert>
                  </TableCell>
                </TableRow>
              ) : (
                filteredLogs.map((log: AuditLog) => (
                  <TableRow key={log.id} hover>
                    <TableCell>
                      <Typography variant="body2">
                        {format(new Date(log.createdAt), 'yyyy-MM-dd HH:mm:ss', { locale: zhCN })}
                      </Typography>
                    </TableCell>
                    <TableCell>
                      <Chip
                        icon={getLevelIcon(log.level)}
                        label={log.level.toUpperCase()}
                        size="small"
                        color={getLevelColor(log.level) as any}
                        variant="outlined"
                      />
                    </TableCell>
                    <TableCell>
                      <Typography variant="body2">
                        {getActionText(log.action)}
                      </Typography>
                    </TableCell>
                    <TableCell>
                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                        <Avatar sx={{ width: 24, height: 24 }}>
                          <PersonIcon fontSize="small" />
                        </Avatar>
                        <Typography variant="body2">
                          {log.user?.name || '系统'}
                        </Typography>
                      </Box>
                    </TableCell>
                    <TableCell>
                      <Typography 
                        variant="body2" 
                        sx={{ 
                          maxWidth: 200, 
                          overflow: 'hidden', 
                          textOverflow: 'ellipsis',
                          whiteSpace: 'nowrap'
                        }}
                      >
                        {log.description}
                      </Typography>
                    </TableCell>
                    <TableCell>
                      <Typography variant="body2" color="text.secondary">
                        {log.ipAddress}
                      </Typography>
                    </TableCell>
                    <TableCell align="center">
                      <Tooltip title="查看详情">
                        <IconButton
                          size="small"
                          onClick={() => handleViewDetail(log)}
                        >
                          <VisibilityIcon fontSize="small" />
                        </IconButton>
                      </Tooltip>
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </TableContainer>
        
        <TablePagination
          component="div"
          count={total}
          page={page}
          onPageChange={handlePageChange}
          rowsPerPage={pageSize}
          onRowsPerPageChange={handlePageSizeChange}
          rowsPerPageOptions={[5, 10, 25, 50]}
          labelDisplayedRows={({ from, to, count }) => `${from}-${to} 共 ${count} 条`}
          labelRowsPerPage="每页显示:"
        />
      </Card>

      {/* 日志详情对话框 */}
      <Dialog
        open={detailDialogOpen}
        onClose={() => setDetailDialogOpen(false)}
        maxWidth="md"
        fullWidth
      >
        <DialogTitle>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
            <HistoryIcon />
            审计日志详情
          </Box>
        </DialogTitle>
        <DialogContent>
          {selectedLog && (
            <Grid container spacing={2}>
              <Grid item xs={12} sm={6}>
                <Typography variant="subtitle2" color="text.secondary">
                  操作时间
                </Typography>
                <Typography variant="body2">
                  {format(new Date(selectedLog.createdAt), 'yyyy年MM月dd日 HH:mm:ss', { locale: zhCN })}
                </Typography>
              </Grid>
              <Grid item xs={12} sm={6}>
                <Typography variant="subtitle2" color="text.secondary">
                  日志级别
                </Typography>
                <Chip
                  icon={getLevelIcon(selectedLog.level)}
                  label={selectedLog.level.toUpperCase()}
                  size="small"
                  color={getLevelColor(selectedLog.level) as any}
                  variant="outlined"
                />
              </Grid>
              <Grid item xs={12} sm={6}>
                <Typography variant="subtitle2" color="text.secondary">
                  操作类型
                </Typography>
                <Typography variant="body2">
                  {getActionText(selectedLog.action)}
                </Typography>
              </Grid>
              <Grid item xs={12} sm={6}>
                <Typography variant="subtitle2" color="text.secondary">
                  操作用户
                </Typography>
                <Typography variant="body2">
                  {selectedLog.user?.name || '系统'}
                </Typography>
              </Grid>
              <Grid item xs={12} sm={6}>
                <Typography variant="subtitle2" color="text.secondary">
                  IP 地址
                </Typography>
                <Typography variant="body2">
                  {selectedLog.ipAddress}
                </Typography>
              </Grid>
              <Grid item xs={12} sm={6}>
                <Typography variant="subtitle2" color="text.secondary">
                  用户代理
                </Typography>
                <Typography variant="body2" sx={{ wordBreak: 'break-all' }}>
                  {selectedLog.userAgent || '未知'}
                </Typography>
              </Grid>
              <Grid item xs={12}>
                <Typography variant="subtitle2" color="text.secondary">
                  操作描述
                </Typography>
                <Typography variant="body2">
                  {selectedLog.description}
                </Typography>
              </Grid>
              {selectedLog.metadata && (
                <Grid item xs={12}>
                  <Accordion>
                    <AccordionSummary expandIcon={<ExpandMoreIcon />}>
                      <Typography variant="subtitle2">详细信息</Typography>
                    </AccordionSummary>
                    <AccordionDetails>
                      <Paper sx={{ p: 2, bgcolor: 'grey.50' }}>
                        <pre style={{ margin: 0, fontSize: '0.875rem', overflow: 'auto' }}>
                          {JSON.stringify(selectedLog.metadata, null, 2)}
                        </pre>
                      </Paper>
                    </AccordionDetails>
                  </Accordion>
                </Grid>
              )}
            </Grid>
          )}
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDetailDialogOpen(false)}>
            关闭
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default AuditLogsPage;